package block

import (
	"learn-opengl/object/item"
	"learn-opengl/opengl/shader"
	"learn-opengl/opengl/vertexArray"
	"learn-opengl/opengl/vertexBuffer"

	"github.com/go-gl/gl/v3.3-core/gl"
	"github.com/go-gl/mathgl/mgl32"
)

var Blocks = make([]*Block,65)

type Block struct {
	vao *vertexArray.VertexArray
	data []float32
}

func Build() {
	for i:=1;i<=64;i++ {
		Blocks[i] = NewBlock(i)
	}
}

func NewBlock(id int) *Block {
	block := &Block{}
	var data []float32
	if id>=17 && id <= 23 {
		data = item.MakePlantData([]float32{},item.Tex.Texture(id))
	} else {
		data = item.MakeCubeData([]float32{}, item.Tex.Texture(id))
	}
	block.data = data

	vbo := vertexBuffer.NewVertexBuffer(data)
	block.vao = vertexArray.NewVertexArray()
	block.vao.Bind()
	vbo.Bind()
	
	gl.VertexAttribPointer(0,3,gl.FLOAT,false,32,gl.PtrOffset(0))
	gl.EnableVertexAttribArray(0)
	gl.VertexAttribPointer(1,2,gl.FLOAT,false,32,gl.PtrOffset(12))
	gl.EnableVertexAttribArray(1)
	gl.VertexAttribPointer(2,3,gl.FLOAT,false,32,gl.PtrOffset(20))
	gl.EnableVertexAttribArray(2)
	
	return block
}

func (b *Block) Draw(shader *shader.Shader,pos mgl32.Vec3) {
	model := mgl32.Translate3D(pos[0],pos[1],pos[2])
	shader.SetUniformMat4f("model",model)
	b.vao.Bind()
	gl.DrawArrays(gl.TRIANGLES,0,int32(len(b.data)/8))
}
